import { Injectable, Logger } from "@nestjs/common";
import { Cron, Interval, Timeout, SchedulerRegistry } from "@nestjs/schedule";
import { CronJob } from "cron";

@Injectable()
export class TasksService {
    constructor(private schedulerRegistry: SchedulerRegistry) {

    }

    private readonly logger = new Logger(TasksService.name);

    @Cron('*/10 * * * * *', {
        name: 'notifications'
    })
    notifications() {
        this.logger.debug('Called when the current second is 42');
    }

    // @Interval(1000)
    // handleInterval() {
    //     this.logger.debug('Called every 1000ms');
    // }

    @Timeout(50000)
    handleTimeout() {
        // 使用schedulerRegistry动态调度任务
        const job = this.schedulerRegistry.getCronJob('notifications');

        job.stop();
        console.log(job.lastDate());
    }

    // 创建动态cron
    addCronJob(name: string, seconds: string) {
        // const job = new CronJob(seconds, () => {
        //     this.logger.debug(`Called when the current second is ${seconds}`);
        // });

        // this.schedulerRegistry.addCronJob(name, job);
        // job.start();
    }
}